import 'dart:async';

import 'package:flutter/material.dart';

import 'sliver_header.dart';

class SliverCategoryExample extends StatefulWidget {
  const SliverCategoryExample({super.key});

  @override
  State<SliverCategoryExample> createState() => _SliverCategoryExampleState();
}

class _SliverCategoryExampleState extends State<SliverCategoryExample> {
  final top = ValueNotifier(200.0);
  static const leftMenuWidth = 150.0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          NotificationListener<ScrollNotification>(
            onNotification: (notifaction) {
              if (notifaction is ScrollUpdateNotification) {
                var value = 200 - notifaction.metrics.extentBefore;
                if (value < 0) {
                  value = 0;
                }
                top.value = value;
              }
              return true;
            },
            child: CustomScrollView(
              slivers: <Widget>[
                SliverWrapper(
                  builder: (BuildContext context, double shrinkOffset,
                      bool overlapsContent) {
                    // notifierChange(shrinkOffset);
                    return Container(
                      height: double.infinity,
                      color: Colors.grey,
                      child: const Text('标题'),
                    );
                  },
                  maxHeight: 200,
                  minHeight: 100,
                ),
                SliverPadding(
                  sliver: _buildList(),
                  padding: const EdgeInsets.only(left: leftMenuWidth),
                ),
              ],
            ),
          ),
          AnimatedBuilder(
            animation: top,
            builder: (_, __) => Positioned(
              left: 0,
              width: leftMenuWidth,
              top: top.value,
              bottom: 0,
              child: Container(
                color: Colors.grey.withOpacity(0.5),
                child: ListView.builder(
                  itemBuilder: (BuildContext context, int index) {
                    return Text("一级菜单: $index");
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildList() {
    return SliverList(
      delegate: SliverChildBuilderDelegate(
        _buildItem,
        childCount: 100,
      ),
    );
  }

  Widget _buildItem(BuildContext context, int index) {
    return ListTile(
      title: Text(index.toString()),
    );
  }

  Future<void> notifierChange(double shrinkOffset) async {
    Timer(Duration.zero, () {
      top.value = 200 - shrinkOffset;
    });
  }
}
